<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item prop="buildId" label="告警类型：">
        <el-select v-model="queryParams.alarmType" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.alarm_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="unitId" label="告警等级：">
        <el-select v-model="queryParams.alarmLevel" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.alarm_level" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 10px;display: flex;justify-content: space-between;">
      <div>
        <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline"
          @click="dialogVisible = true; formData = {}; title = '添加告警类型'">添加告警类型</el-button>
        <el-button type="primary" size="mini" icon="el-icon-circle-close" @click="piliangDel">批量删除</el-button>
        <!--<el-button type="primary" size="mini" icon="el-icon-circle-close" @click="lianjie">连接</el-button>-->
        <!--<el-button type="primary" size="mini" icon="el-icon-circle-close" @click="send">发送</el-button>-->
      </div>

      <div>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="showSearch = !showSearch"></el-button>
        <el-button type="primary" size="mini" icon="el-icon-refresh-right" @click="getList"></el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column v-if="selectFlag" type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index"></el-table-column>
      <el-table-column show-overflow-tooltip label="告警种类" align="center" prop="alarmTypeName" />
      <el-table-column label="告警等级" align="center" prop="alarmLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.alarm_level" :value="scope.row.alarmLevel" />
        </template>
      </el-table-column> <el-table-column show-overflow-tooltip label="创建人" align="center"
        prop="createName"></el-table-column>
      <el-table-column show-overflow-tooltip label="创建时间" align="center" prop="createTime" />
      <el-table-column show-overflow-tooltip label="推送" align="center" prop="pushStatus">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.pushStatus" :active-value="'0'" :inactive-value="'1'"
            @change="switchChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="检查字段" align="center" prop="checkField"></el-table-column>
      <el-table-column show-overflow-tooltip label="描述" align="center" prop="remark"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handelEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加编辑告警 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="50%" append-to-body>
      <el-form :model="formData" ref="formData" :rules="formDataRule" size="small" label-position="left"
        label-width="120px" style="display: flex;flex-wrap: wrap;">
        <el-form-item @change="alarmTypeChange" prop="alarmType" label="告警种类：" style="padding-left: 30px;min-width: 50%;">
          <el-select v-model="formData.alarmType" placeholder="请选择告警种类" clearable>
            <el-option v-for="dict in dict.type.alarm_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.alarmType == 1" prop="equipmentType" label="设备类型："
          style="padding-left: 30px;min-width: 50%;">
          <el-select v-model="formData.equipmentType" placeholder="请选择设备类型" clearable>
            <el-option v-for="dict in dict.type.protocol_type" :key="dict.value" :label="dict.label.replace('协议', '')"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.alarmType == 3" prop="equipmentType" label="告警类型："
          style="padding-left: 30px;min-width: 50%;">
          <el-select v-model="formData.equipmentType" placeholder="请选择设备类型" clearable>
            <el-option v-for="dict in dict.type.control_tactics" :key="dict.value" :label="dict.label.replace('协议', '')"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.alarmType == 2" prop="indexType" label="告警类型：" style="padding-left: 30px;min-width: 50%;">
          <el-select v-model="formData.indexType" placeholder="请选择告警类型" clearable>
            <el-option v-for="dict in dict.type.control_tactics" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.alarmType == 1" prop="exceedTimes" label="设备断联次数："
          style="padding-left: 30px;min-width: 50%;">
          <el-input placeholder="请输入设备断联次数" type="number" v-model="formData.exceedTimes"></el-input>
        </el-form-item>
        <!-- <el-form-item v-if="formData.alarmType == 3" prop="targetValue" label="目标值："
          style="padding-left: 30px;min-width: 50%;">
          <el-input placeholder="请输入目标值" type="number" v-model="formData.targetValue"></el-input>
        </el-form-item> -->
        <el-form-item v-if="formData.alarmType == 3" prop="fluctuatingValue" label="波动值："
          style="padding-left: 30px;min-width: 50%;">
          <el-input placeholder="请输入波动值" type="number" v-model.number="formData.fluctuatingValue"></el-input>
        </el-form-item>
        <el-form-item v-if="formData.alarmType == 2" prop="minValue" label="最小值："
          style="padding-left: 30px;min-width: 50%;">
          <el-input placeholder="请输入最小值" type="number" v-model="formData.minValue"></el-input>
        </el-form-item>
        <el-form-item v-if="formData.alarmType == 2" prop="maxValue" label="最大值："
          style="padding-left: 30px;min-width: 50%;">
          <el-input placeholder="请输入最大值" type="number" v-model="formData.maxValue"></el-input>
        </el-form-item>
        <el-form-item label="告警等级：" prop="alarmLevel" style="padding-left: 30px;min-width: 50%;">
          <el-select v-model="formData.alarmLevel" placeholder="请选择" clearable>
            <el-option v-for="dict in dict.type.alarm_level" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否推送：" prop="pushStatus" style="padding-left: 30px;min-width: 50%;">
          <el-select v-model="formData.pushStatus" placeholder="请选择是否推送" clearable>
            <el-option v-for="dict in sys_one_zero" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="formData.pushStatus == 0" label="推送间隔：" prop="pushInterval"
          style="padding-left: 30px;min-width: 50%;">
          <el-input min="0" type="number" v-model="formData.pushInterval" placeholder="请设置几分钟推送一次"></el-input>
        </el-form-item>
        <el-form-item v-if="formData.alarmType != 1 && formData.alarmType != 4" label="检查字段：" prop="checkField" style="padding-left: 30px;min-width: 50%;">
          <el-input v-model="formData.checkField" placeholder="请输入检查字段"></el-input>
        </el-form-item>
        <el-form-item label="描述：" prop="remark" style="padding-left: 30px;min-width: 50%;">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isOk">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
// import { warnSettingList } from "@/api/mock"
import {
  listAlarmSetting, getAlarmSetting, addAlarmSetting,
  updateAlarmSetting, delAlarmSetting, editPushStatus
} from "@/api/alarmSetting/alarmSetting"
import { number } from 'echarts'

export default {
  dicts: ['alarm_level', 'equipment_type', 'sys_one_zero', 'alarm_type', 'control_tactics', 'protocol_type'],
  data() {
    return {
      selectFlag: false,
      dialogVisible: false,
      visible: false,
      showSearch: true,
      xiaoquData: [],
      leixdata: [
        { label: '故障告警', value: 0 },
        { label: '传感器告警', value: 1 },
        { label: '数据异常告警', value: 2 },
      ],
      dengjidata: [
        { label: '一般', value: 0 },
        { label: '严重', value: 1 },
        { label: '紧急', value: 2 }
      ],
      statusData: [
        { label: '未处理', value: 0 },
        { label: '已处理', value: 1 },
      ],
      sys_one_zero: [
        { label: '是', value: '0', }, { label: '否', value: '1', }
      ],
      total: 0,
      loading: false,
      queryParams: {
        alarmLevel: null,
        alarmType: null,
        pageNum: 1,
        pageSize: 10,
      },
      typeList: [
      ],
      yinData: [
        { label: '隐藏', value: 0 },
        { label: '推送', value: 1 }
      ],
      ids: [],
      title: '添加告警类型',
      formData: {
        alarmType: '',
        indexType: '',
        exceedTimes: '',
        pushStatus: '',
        targetValue: '',
        alarmLevel: '',
        remark: '',
        pushInterval: '',
        fluctuatingValue: '',
        minValue: '',
        maxValue: '',
        equipmentType: '',
        checkField:""
      },
      formDataRule: {
        alarmType: [
          { required: true, message: '请选择告警种类', trigger: 'blur' },
        ],
        indexType: [
          { required: true, message: '请选择告警类型', trigger: 'blur' },
        ],
        equipmentType: [
          { required: true, message: '请选择设备类型', trigger: 'blur' },
        ],
        pushStatus: [
          { required: true, message: '请选择是否推送', trigger: 'blur' },
        ],
        alarmLevel: [
          { required: true, message: '请选择告警等级', trigger: 'blur' },
        ],
        exceedTimes: [
          { required: true, message: '请输入设备断连次数', trigger: 'blur' },
        ],
        targetValue: [
          { required: true, message: '请输入目标值', trigger: 'blur' },
        ],
        fluctuatingValue: [
          { required: true, message: '请输入波动值', trigger: 'blur' },
          { pattern:/^(?:[0-9]|1[0-5])$/,message: '请输入正确的波动值,0到15',trigger: 'blur'},
        ],
        pushInterval: [
          { required: true, message: '请输入推送间隔', trigger: 'blur' },
        ],
        minValue: [
          { required: true, message: '请输入波动范围最小值', trigger: 'blur' },
        ],
        maxValue: [
          { required: true, message: '请输入波动范围最大值', trigger: 'blur' },
        ],
      },
      info: {
        shichang: ''
      },
      flagInfo: true,
      infoRules: {
        shichang: [
          { required: true, message: '请输入告警等级', trigger: 'blur' },
        ],
      },
      ws: null
    }
  },
  computed: {

  },
  created() {
    this.getList();
  },
  methods: {
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        alarmLevel: null,
        alarmType: null,
        pageNum: 1,
        pageSize: 10,
      };
      this.getList();
    },
    // 改变推送状态
    switchChange(row) {
      let { id, pushStatus } = row
      editPushStatus({ id, pushStatus }).then(res => {
        this.$message.success('修改成功')
      }, err => {
        row.pushStatus == '0' ? row.pushStatus = '1' : row.pushStatus = '0'
        this.$message.error('修改失败')
      })
      console.log(row)
    },
    // 编辑
    handelEdit(row) {
      this.title = '编辑告警类型'
      this.dialogVisible = true
      console.log("编辑",row);
      this.formData = row
    },
    // 编辑添加确认
    isOk() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          if (this.formData.pushStatus == 1) this.formData.pushInterval = 0
          if (this.formData.id != null) {
            updateAlarmSetting(this.formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.getList();
            });
          } else {
            addAlarmSetting(this.formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.getList();
            });
          }
        }
      })
    },
    // 设置时长
    shezhiOk() {
      this.$refs['infoForm'].validate((valid) => {
        console.log(valid);
      })
    },
    // 多选框数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      // console.log(this.ids);
    },
    // 处理/查看（flag:true  处理  flag:false  查看）
    huifu(row, flag) {
      this.formData = row
      if (flag) {
        console.log('处理');
        this.flagInfo = false
        this.title = '告警处理'
      }

      if (!flag) {
        console.log('查看');
        this.flagInfo = true
        this.title = '告警查看'
      }
      this.dialogVisible = true
    },
    //批量删除
    piliangDel() {
      const ids = this.ids;
      if (this.ids.length === 0) {
        this.selectFlag = !this.selectFlag
      } else {
        this.$modal.confirm('是否删除所选数据？').then(function () {
          return delAlarmSetting(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      }
    },
    //
    lianjie() {
      const wsuri = "ws://127.0.0.1:6010/websocket/message/1";
      this.ws = new WebSocket(wsuri);
      const self = this;
      this.ws.onopen = function (event) {
        self.text_content = self.text_content + "已经打开连接!" + "\n";
      };
      this.ws.onmessage = function (event) {
        self.text_content = event.data + "\n";
        console.log("收到消息：", event.data)
      };
      this.ws.onclose = function (event) {
        self.text_content = self.text_content + "已经关闭连接!" + "\n";
      };
    },
    //批量删除
    send() {
      if (this.ws) {
        this.ws.send(this.queryParams.alarmTypeName);
      } else {
        alert("未连接到服务器");
      }
    },
    // 操作栏，单个删除
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否删除此条数据？删除后不可恢复。').then(function () {
        return delAlarmSetting(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 获取列表数据
    getList() {
      this.loading = true;
      listAlarmSetting(this.queryParams).then(response => {
        // warnSettingList(this.queryParams).then(response => {
        this.typeList = response.rows;
        this.total = response.total;
        this.loading = false;
      }, err => {
        this.loading = false;
      });
    },
    alarmTypeChange() {
      // for (const key in this.formData) {
      //   if (key != 'alarmType' && key != 'remark') {
      //     this.formData[key] = ''
      //   }
      // }
    }
  },
}
</script>

<style lang="scss" scoped>
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

::v-deep input[type='number'] {
  -moz-appearance: textfield !important;
}

::v-deep .el-dialog .el-form .el-form-item .el-form-item__label {
  width: 120px !important;
}

::v-deep .el-dialog .el-form .el-form-item .el-form-item__content {
  margin-left: 120px !important;
}
</style>
